﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.ServiceModel;
using System.Windows.Forms;
using TrifleCommon;

namespace TrifleWCFWindowsServiceHost
{
    
    public partial class TrifleService : ServiceBase
    {
        #region ------ 服务配置（只需配置这里即可） ------

        /// <summary>
        /// 最大重启次数
        /// </summary>
        static int MaxRestartCount = 3;

        /// <summary>
        /// WCF服务的名字
        /// </summary>
        static string WCFServiceName = "TrifleWCF";

        /// <summary>
        /// 实现WCF契约的类
        /// </summary>
        static Type WCFServiceClassType = typeof(TrifleWCF.Trifle);

        #endregion


        #region ------ 常量配置、初始化区 ------


        static readonly string MSG_WCFOpen_Notice =
            "====== 开始启动 <" + WCFServiceName + "> WCF服务 ======";

        static readonly string MSG_WCFOpen_Success = "启动成功...";

        static readonly string MSG_WCFOpen_Err = "启动异常";

        static readonly string MSG_WCFReOpen_Notice = "---- 尝试重启 ----";

        //{0}: 启动次数
        static readonly string MSG_P_WCFReOpen = "-- 第<{0}>次尝试重启 --";

        //{0}: 启动次数
        static readonly string MSG_P_WCFReOpen_StopReOpen = "重启<{0}>次失败 不再重启";

        static readonly string MSG_WCFClose_Notice = "尝试关闭";

        static readonly string MSG_WCFClose_Success = "<" + WCFServiceName + "> WCF服务已关闭";

        static readonly string MSG_WCFClose_Err = "关闭异常";

        static readonly string MSG_WCF_Err = "WCF服务异常";

        static readonly string MSG_WCFRuntime_Err = "WCF服务运行时异常";

        static readonly string MSG_WCFRuntime_Err_Err = "WCF服务运行时异常处理异常";


        #endregion ------ 常量配置、初始化区 ------




        public TrifleService()
        {
            InitializeComponent();
        }

        /// <summary>
        /// WCF服务宿主
        /// </summary>
        ServiceHost host = null;

        /// <summary>
        /// 指示WCF服务是否正在运行
        /// </summary>
        bool bWCFRunning = false;



        protected override void OnStart(string[] args)
        {
            TryStartWCFService(WCFServiceClassType);
        }

        /// <summary>
        /// Windows服务停止时触发
        /// </summary>
        protected override void OnStop()
        {
            try
            {
                if (host != null && host.State != CommunicationState.Closed)
                {
                    //停止WCF服务
                    Logger.Info(MSG_WCFClose_Notice);
                    host.Close();
                }
            }
            catch (Exception e)
            {
                Logger.Exception(MSG_WCFClose_Err, e);
            }
        }

        /// <summary>
        /// 尝试启动WCF服务
        /// </summary>
        /// <param name="wcfService"></param>
        /// <param name="tryTimes"></param>
        private bool TryStartWCFService(Type wcfService)
        {
            Logger.Info(MSG_WCFOpen_Notice);
            if (StartWCFService(wcfService))
            {
                return true;
            }
            else
            {
                int count = 1;
                while (count <= MaxRestartCount)
                {
                    Logger.Info(string.Format(MSG_P_WCFReOpen, count));
                    if (StartWCFService(wcfService))
                        return true;
                    count++;
                }
                Logger.Exception(string.Format(MSG_P_WCFReOpen_StopReOpen, MaxRestartCount), "");
                return false;
            }
        }

        /// <summary>
        /// 启动服务的方法
        /// </summary>
        private bool StartWCFService(Type wcfService)
        {
            try
            {
                host = new ServiceHost(wcfService);
                host.Opened += delegate
                {
                    Logger.Info(MSG_WCFOpen_Success);
                    bWCFRunning = true;
                };
                host.Closed += delegate
                {
                    Logger.Info(MSG_WCFClose_Success);
                    bWCFRunning = false;
                };
                host.Open();
                return true;
            }
            catch (Exception e)
            {
                Logger.Exception(MSG_WCFOpen_Err, e);
                return false;
            }
        }

    }
}
